package com.szx.kaihei.intercepter;

import cn.hutool.core.convert.Convert;
import com.szx.kaihei.constants.JwtConstant;
import com.szx.kaihei.exceptions.CustomException;
import com.szx.kaihei.exceptions.ExceptionEnums;
import com.szx.kaihei.pojo.User;
import com.szx.kaihei.util.JwtUtil;
import com.szx.kaihei.util.UserLocalStorageUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

public class AccessIntercepter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //请求头获取jwt令牌
        String jwt = request.getHeader(JwtConstant.JWT_HEADER);
        if (jwt == null && !JwtUtil.validateToken(jwt)) {
            throw new CustomException(ExceptionEnums.USER_NOT_LOGIN);
        }
        Long id = Convert.toLong(JwtUtil.getClaim(jwt, "id"));
        String name = Convert.toStr(JwtUtil.getClaim(jwt, "name"));
        User user = User.builder().id(id).nickname(name).build();
        UserLocalStorageUtil.set(user);
        return true;
    }
}
